package com.sohu.pickoo.frag;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.StatefulJob;
import org.quartz.impl.StdSchedulerFactory;

import com.sohu.peak.util.ConfigManager;
import com.sohu.peak.util.Logger;

public class GetFragJob implements StatefulJob  {

	private static Logger log = new Logger();
	
	private static SchedulerFactory sf = new StdSchedulerFactory();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * Quartz requires a public empty constructor so that the
     * scheduler can instantiate the class whenever it needs.
     */
    public GetFragJob() {
    }

    /**
     * <p>
     * Called by the <code>{@link org.quartz.Scheduler}</code> when a
     * <code>{@link org.quartz.Trigger}</code> fires that is associated with
     * the <code>Job</code>.
     * </p>
     * 
     * @throws JobExecutionException
     *             if there is an exception while executing the job.
     */
    public void execute(JobExecutionContext context)
        throws JobExecutionException {
    	JobDataMap dataMap2 = context.getJobDetail().getJobDataMap();
    	Date mTime = (Date)dataMap2.get("mTime");
    	Date maxTime = mTime;
		try {
			maxTime = addFragJob(mTime);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dataMap2.clear();
		dataMap2.put("mTime", maxTime);
		context.getJobDetail().setJobDataMap(dataMap2);
		/*Scheduler sched = null;
		try {
			sched = sf.getScheduler();
			JobDetail job = sched.getJobDetail("getFragjob", "group3");
			job.setJobDataMap(dataMap2);
		} catch (SchedulerException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}*/

    	
    	log.debug("最新更新时间："+sdf.format(maxTime));
    	String jobName = context.getJobDetail().getFullName();
    	log.debug("定时获取碎片job says: " + jobName + " executing at " + new Date());         
    }
    
    public Date addFragJob(Date mTime) throws Exception {

        log.debug("------- 读取数据库设置定时碎片刷新-------------------");

        // First we must get a reference to a scheduler
        
        
        Scheduler sched = sf.getScheduler();
        
        java.sql.Connection   lConn   =   null;   
        java.sql.Statement   lStat   =   null; 
		Class driverClass;
		driverClass = Class.forName(ConfigManager.instance().getProperty(
				"newfrag", "pickooDB.dirver"));
		DriverManager.registerDriver((Driver) driverClass.newInstance());
		lConn = DriverManager.getConnection(ConfigManager.instance()
				.getProperty("newfrag", "pickooDB.url"), ConfigManager
				.instance().getProperty("newfrag", "pickooDB.user"),
				ConfigManager.instance().getProperty("newfrag",
						"pickooDB.passwd"));
        lStat   =   lConn.createStatement();   

        log.debug("------- 连接数据库成功--------");
		
        ResultSet rs = lStat.executeQuery("select * from FRAG_NEW where is_stop=0 ");
        
        Date maxTime = mTime;
        log.debug("mTime="+sdf.format(mTime));
        if (rs!=null){
        	while (rs.next()){
        		if(rs.getTimestamp("mTime").compareTo(mTime)>0)	//如果记录修改时间大于最大修改时间，则更新job
        		{
        			if(sched.getJobDetail("fragjob_"+rs.getString("id"), "group2")!=null)
        				this.removeJob("fragjob_"+rs.getString("id"), "group2", "fragtrigger_"+rs.getString("id"), "group2");
        			
        			log.debug("-------新增 Job "+rs.getString("id")+"----------------");
            		
        			JobDetail job = new JobDetail("fragjob_"+rs.getString("id"), "group2", NewFragJob.class);
            		JobDataMap dataMap = new JobDataMap();
            		dataMap.put("source",rs.getString("source"));
            		dataMap.put("target",rs.getString("target"));
            		job.setJobDataMap(dataMap);
            		CronTrigger trigger = new CronTrigger("fragtrigger_"+rs.getString("id"), "group2", "fragjob_"+rs.getString("id"),
                            "group2", rs.getString("timer"));
                    sched.addJob(job, true);
                    Date ft = sched.scheduleJob(trigger);
                    log.debug(job.getFullName() + " has been scheduled to run at: " + ft
                            + " and repeat based on expression: "
                            + trigger.getCronExpression());
                    
                    if(rs.getTimestamp("mTime").compareTo(maxTime)>0) maxTime=rs.getTimestamp("mTime");
                    log.debug("maxTime="+sdf.format(maxTime));
        		}
        	}    	
        }
 
        log.debug("------- Starting Scheduler ----------------");

        // All of the jobs have been added to the scheduler, but none of the
        // jobs
        // will run until the scheduler has been started
        sched.start();
       
        log.debug("------- Started Scheduler -----------------");

        log.debug("------- Waiting For Executing... ------------");
        /*try {
        	while (true){
        		// wait five minutes for executing
        		Thread.sleep(300L * 1000L);
        		// executing...
        	}
        } catch (Exception e) {
        }*/
        return maxTime;
    }
    
    /** *//**
     * 移除一个任务
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     * @throws SchedulerException
     */
    public void removeJob(String jobName,String jobGroupName,
                                 String triggerName,String triggerGroupName) 
                                throws SchedulerException{
        Scheduler sched = sf.getScheduler();
        sched.pauseTrigger(triggerName,triggerGroupName);//停止触发器
        sched.unscheduleJob(triggerName,triggerGroupName);//移除触发器
        sched.deleteJob(jobName,jobGroupName);//删除任务
        log.debug("------- 删除job--"+jobName+"----------------");
    }


}
